package com.kongyz.app;

import com.kongyz.client.RpcClient;
import com.kongyz.client.RpcFuture;
import com.kongyz.client.proxy.IAsyncObjectProxy;
import com.kongyz.registry.ServiceDiscovery;
import com.kongyz.rpc.HelloService;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author kongyz
 * @date 2018/9/10 22:04
 * @Description:
 */
public class BenchmarkAsync {
    public static void main(String[] args) throws InterruptedException {
        ServiceDiscovery serviceDiscovery=new ServiceDiscovery("10.25.2.128:2181");
        final RpcClient rpcClient=new RpcClient(serviceDiscovery);

        int threadNum=10;
        final int requestNum=100;
        Thread[] threads=new Thread[threadNum];

        long startTime=System.currentTimeMillis();

        for (int i=0;i<threadNum;i++){
            threads[i]=new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0;i<requestNum;i++){
                        IAsyncObjectProxy client=rpcClient.createAsync(HelloService.class);
                        RpcFuture helloFuture=client.call("hello",Integer.toString(i));
                        String result= null;
                        try {
                            result = (String) helloFuture.get(3000,TimeUnit.MILLISECONDS);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        } catch (TimeoutException e) {
                            e.printStackTrace();
                        }
                        if(!result.equals("Hello! "+i)){
                            System.out.println("错误 = "+result);
                        }
                        System.out.println("返回结果："+result);
                    }
                }
            });
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        long timeCost = (System.currentTimeMillis() - startTime);
        String msg = String.format("Sync call total-time-cost:%sms, req/s=%s", timeCost, ((double) (requestNum * threadNum)) / timeCost * 1000);
        System.out.println(msg);

        rpcClient.stop();
    }
}
